<?php

namespace Common\Middleware\Auth;


use _PHPStan_95cdbe577\Nette\DI\Attributes\Inject;
use Common\Helpers\DebugHelper;
use Common\Services\AuthServer;
use Common\Services\JwtService;
use Common\Services\Sys\ProjectService;
use Common\WebSocket\Utility\VerifyProject;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Router\Dispatched;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;


class AuthMiddleware implements MiddlewareInterface{

    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!$request->getAttribute('authOptional')){
            return $handler->handle($request);
        }
        $request = Context::get(ServerRequestInterface::class);
        $callback = $request->getAttribute(Dispatched::class)->handler->callback;
        [$class,$action] = $callback;
        //        特殊放行
        if($class === "App\\WebSocketController\\IndexController"){
            return $handler->handle($request);
        }


        /**
         * 获取请求的域名
         */
        $referer =$request->getHeaderLine('referer');
        $domain = parse_url($referer);
        $token = $request->getHeaderLine('access-token');
        $project_sn = $this->request->route('project_sn');
        DebugHelper::consoleWrite('项目权限校验',[
            $request->getHeaders(),
            'project_sn'=>$project_sn,
        ]);
        $AuthServer = new AuthServer();

        $project = $AuthServer->checkProjectAuth($project_sn,$domain['host']??'',$token);
        DebugHelper::consoleWrite('项目权限校验完成',[
            'project'=>$project,
            'token'=>$token,
            'project_sn'=>$project_sn,
            'domain'=>$domain
        ]);

        if($project['code'] === 200){
            $project_id = $project['data']['project']['id'];
            $user = $project['data']['user'];
            DebugHelper::consoleWrite('项目信息',[
                'project_id' => $project_id
            ]);
            $request = $request->withAttribute('project_id',$project_id);
            $request = $request->withAttribute('user',$user);
            Context::set(ServerRequestInterface::class, $request);
            return $handler->handle($request);
        }else{
            return $this->response->json($project);
        }

    }
}